package cn.wolfcode.wolf2w.gateway.filter;

import cn.wolfcode.wolf2w.common.core.domain.R;
import cn.wolfcode.wolf2w.common.redis.service.RedisService;
import cn.wolfcode.wolf2w.common.redis.util.RedisKeys;
import com.alibaba.fastjson2.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;


@Component
public class BrushFilter implements GlobalFilter {

    @Autowired
    private RedisService redisService;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取请求头
        String url = exchange.getRequest().getURI().getPath();
        String ip = exchange.getRequest().getRemoteAddress().getAddress().toString();
        String key = RedisKeys.BRUSH.join(url, ip);
        redisService.setnxacheObject(key,20,RedisKeys.BRUSH.getTime(), TimeUnit.SECONDS);
        Long d = redisService.decrCacheObject(key);
        if (d <= 0) {
            //获取请求头
            HttpHeaders headers = exchange.getResponse().getHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            R<Object> r = R.fail(500, "请勿频繁刷新");
            String jsonString = JSON.toJSONString(r);
            //byte[]
            byte[] bytes = jsonString.getBytes(StandardCharsets.UTF_8);
            //写入DataBuffer
            DataBuffer data = exchange.getResponse().bufferFactory().wrap(bytes);
            //返回结果
            return exchange.getResponse().writeWith(Mono.just(data));
        }
        return chain.filter(exchange);
//        return null;
    }

}
